﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using ProgrammingEducationSystem.Dto;
using ProgrammingEducationSystem.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace ProgrammingEducationSystem.Controllers
{
    //用户登录注册控制器
    [Route("api/[controller]")]
    [ApiController]
    public class AuthsController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;
        private readonly RoleManager<Role> _roleManager;

        public AuthsController(UserManager<User> userManager, SignInManager<User> signInManager, IMapper mapper, IConfiguration configuration, RoleManager<Role> roleManager)
        {
            _mapper = mapper;
            _userManager = userManager;
            _signInManager = signInManager;
            _configuration = configuration;
            _roleManager = roleManager;
        }


        //学生注册
        [HttpPost("register")]
        public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)
        {
            var reU = await _userManager.FindByNameAsync(userForRegisterDto.UserName);
            if (reU != null) return BadRequest("该用户名已被注册");

            var mapU = _mapper.Map<User>(userForRegisterDto);
            var reCreate = await _userManager.CreateAsync(mapU,userForRegisterDto.Password);
            if (!reCreate.Succeeded)
            {
                Console.WriteLine(reCreate.Errors);
                return BadRequest("注册失败");
            }
            var user = await _userManager.FindByNameAsync(mapU.UserName);
            await _userManager.AddToRoleAsync(user,"STUDENT");
            return Ok("注册成功");
        }

        //用户登录
        [HttpPost("login")]
        public async Task<IActionResult> Login(UserForLoginDto userForLoginDto) 
        {
            var reU = await _signInManager.PasswordSignInAsync(
                userForLoginDto.UserName,
                userForLoginDto.Password,
                false, false
                );
            if (!reU.Succeeded)
            {
                return BadRequest("用户名或密码错误");
            }

            var user = await _userManager.FindByNameAsync(userForLoginDto.UserName);

            var claims = new List<Claim> {
                new Claim(JwtRegisteredClaimNames.Sub,user.Id),
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim("UserId",user.Id),
            };

            var roles = await _userManager.GetRolesAsync(user);

            foreach (var r in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, r));
            }

            var token = new JwtSecurityTokenHandler().WriteToken(
                new JwtSecurityToken(
                    issuer: _configuration["Authentication:Issuer"],
                    audience: _configuration["Authentication:Audience"],
                    claims,
                    notBefore: DateTime.UtcNow,
                    expires: DateTime.UtcNow.AddDays(1),
                    signingCredentials: new SigningCredentials(
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
                            _configuration["Authentication:Secret"]
                            )),
                        SecurityAlgorithms.HmacSha256
                        )
                    )
                );

            return Ok(token);
        }

        //添加老师（注册/修改身份）
        [HttpPost("register/teacher")]
        [Authorize(Roles = "ADMIN")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> RegisterTeacher(UserForRegisterDto userForRegisterDto)
        {
            var reU = await _userManager.FindByNameAsync(userForRegisterDto.UserName);
            if (reU != null) 
            {
                //删除之前的所有角色
                //await _userManager.RemoveFromRolesAsync(reU,
                //      await _userManager.GetRolesAsync(reU)
                //      );

                //  await _userManager.AddToRoleAsync(reU,"TEACHER");

                //  return Ok("已成功添加教师身份");
                return BadRequest("该账号已被注册");
            }
            var mapU = _mapper.Map<User>(userForRegisterDto);
            var reCreate = await _userManager.CreateAsync(mapU,userForRegisterDto.Password);
            if (!reCreate.Succeeded)
            {
                Console.WriteLine(reCreate.Errors);
                return BadRequest("注册失败");
            }
            var user = await _userManager.FindByNameAsync(mapU.UserName);
            await _userManager.AddToRoleAsync(user, "TEACHER");
            return Ok("注册成功");
        }

        //删除学生/老师（注销账户）
        [Authorize(Roles = "ADMIN")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpDelete("WriteOff/{username}")]
        public async Task<IActionResult> WriteOff([FromRoute]string username) {
            var user = await _userManager.FindByNameAsync(username);
            if (user == null) return BadRequest("找不到该用户");
            if ((await _userManager.GetRolesAsync(user)).Contains("ADMIN")) return BadRequest("不可注销管理员账户");
            var reR = await _userManager.DeleteAsync(user);
            if (!reR.Succeeded) {
                Console.WriteLine(reR.Errors);
                return BadRequest("删除异常");
            }
            return Ok("已成功注销用户账户");
        }


    }
}
